/*
 * 入库单明细Repository实现
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.demo.IRepositories;
using VOL.Entity.DomainModels;
using VOL.Core.DbContext;

namespace VOL.demo.Repositories
{
    public partial class StockInOrderItemModelRepository : RepositoryBase<StockInOrderItemModel>, IStockInOrderItemModelRepository, IDependency
    {
        public StockInOrderItemModelRepository(VOLContext dbContext) : base(dbContext)
        {
        }

        public static IStockInOrderItemModelRepository Instance
        {
            get { return AutofacContainerModule.GetService<IStockInOrderItemModelRepository>(); }
        }

        /// <summary>
        /// 批量添加入库明细
        /// </summary>
        public async Task<bool> AddItemsAsync(List<StockInOrderItemModel> items)
        {
            try
            {
                if (items == null || items.Count == 0)
                {
                    Console.WriteLine("批量添加入库明细失败：明细列表为空");
                    return false;
                }

                Console.WriteLine($"=== 开始批量添加入库明细，共 {items.Count} 条 ===");
                
                int result = await DbContext.Insertable(items).ExecuteCommandAsync();
                
                Console.WriteLine($"=== 批量添加完成，影响行数：{result} ===");
                return result > 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"批量添加入库明细失败：{ex.Message}");
                Console.WriteLine($"详细错误：{ex.ToString()}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常：{ex.InnerException.Message}");
                }
                throw;  // 向上抛出异常，让Service层能捕获到详细信息
            }
        }

        /// <summary>
        /// 根据入库单号获取明细
        /// </summary>
        public async Task<List<StockInOrderItemModel>> GetItemsByStockInCodeAsync(string stockInCode)
        {
            try
            {
                return await DbContext.Queryable<StockInOrderItemModel>()
                    .Where(x => x.StockInCode == stockInCode && x.IsDel == 0)
                    .ToListAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取入库明细失败：{ex.Message}");
                return new List<StockInOrderItemModel>();
            }
        }
    }
}

